package com.shuhe.metastore;


import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

//目标库为mysql
public class DbClickHouse {

    private static Logger logger = Logger.getLogger(DbClickHouse.class);


    public static ResultSet querySql(Connection conn, String sql) throws Exception {
        logger.info(sql);
        return conn.createStatement().executeQuery(sql);
    }

    public static Connection connect(String driver, String url, String username, String password) throws Exception {
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }

    public static Connection connectByAll(String url, String username, String password, String driver) throws Exception {
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }


    public static int execSql(Connection conn, String sql) throws Exception {
        logger.info(sql);
        return conn.createStatement().executeUpdate(sql);
    }

    public static int batchExecSql(Connection conn, ArrayList<String> sqls) throws Exception {
        Statement stat = conn.createStatement();
        for (int i = 0; i < sqls.size(); i++) {
            String sql = sqls.get(i);
           // logger.info(sql);
            stat.addBatch(sql);
        }

        stat.executeBatch();
        return 0;
    }

    public static ResultSet querySqlPd(Connection conn, String url, String username, String password, String driver,String sql) {
        try {
            if (conn == null || conn.isClosed()) {
                conn = connectByAll(url, username, password, driver);
            }
            if (!conn.isValid(10)) {
                conn.close();
                conn = connectByAll(url, username, password, driver);
            }
        } catch (Exception ex) {
        }
        try {
            logger.info(sql);
            return conn.createStatement().executeQuery(sql);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static int execSqlPd(Connection conn, String url, String username, String password, String driver,String sql) {
        try {
            if (conn == null || conn.isClosed()) {
                conn = connectByAll(url, username, password, driver);
            }
            if (!conn.isValid(10)) {
                conn.close();
                conn = connectByAll(url, username, password, driver);
            }
        } catch (Exception ex) {
        }
        try {
            logger.info(sql);
            return conn.createStatement().executeUpdate(sql);
        } catch (Exception ex) {
            if (ex.getMessage().indexOf("Duplicate entry") < 0) {
                ex.printStackTrace();
            }
        }
        return 0;
    }


}
